package com.shuang.backtracking9;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class SubsetsWithDup {
    List<List<Integer>> result = new ArrayList<>();// 存放符合条件结果的集合
    LinkedList<Integer> path = new LinkedList<>();// 用来存放符合条件结果
    //用于去重的 标记数组
    boolean[] used;

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        if (nums.length == 0) {
            result.add(path);
            return result;
        }
        //为了去重 首先要对数字数组进行排序
        Arrays.sort(nums);

        used = new boolean[nums.length];

        subsetsWithDupHelper(nums, 0);

        return result;
    }

    private void subsetsWithDupHelper(int[] nums, int startIndex) {
        result.add(new ArrayList<>(path));
        //终止条件
        // if (startIndex >= nums.length) {
        //     return;
        // }
        //for循环
        for (int i = startIndex; i < nums.length; i++) {
            //树层需要去重
            if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
                continue;
            }

            path.add(nums[i]);
            used[i] = true;

            //递归
            subsetsWithDupHelper(nums, i + 1);

            //回溯
            path.removeLast();
            used[i] = false;
        }
    }
}
